package org.edu.modules.system.controller;

import cn.hutool.json.JSONString;
import cn.hutool.json.JSONUtil;
import com.alibaba.druid.sql.PagerUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.ServiceException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.PageList;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.api.client.json.JsonString;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.edu.common.api.vo.Result;
import org.edu.common.aspect.annotation.AutoLog;
import org.edu.common.constant.CommonConstant;
import org.edu.common.system.query.QueryGenerator;
import org.edu.common.system.vo.LoginUser;
import org.edu.common.util.ImportExcelUtil;
import org.edu.common.util.oConvertUtils;
import org.edu.modules.system.entity.*;
import org.edu.modules.system.service.*;
import org.edu.modules.system.service.impl.ProcessInstanceServiceImpl;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.dao.DataAccessException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.SQLException;
import java.util.*;

/**
 * @Author lbh
 * @Date 2025/2/13 上午9:15
 * @Version 1.0
 */
@RestController
@RequestMapping("/sys/processInstance")
@RequiredArgsConstructor
@Api(tags = "流程实例")
@Slf4j
public class ProcessInstanceController {

    private final ProcessInstanceServiceImpl processInstanceService;
    private final IVeBaseAppUserService iVeBaseAppUserService;
    private final IProcessTypeService iProcessTypeService;
    private final IProcessStepService iProcessStepService;
    private final IProcessFormDataService iProcessFormDataService;
    private final ISysAnnouncementService sysAnnouncementService;

    /**
     * 分页列表查询
     *
     * @param processInstance
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "流程实例表-分页列表查询")
    @ApiOperation(value = "流程实例表-分页列表查询", notes = "流程实例表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<ProcessInstance>> queryPageList(ProcessInstance processInstance,
                                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                        HttpServletRequest req) {
        Result<IPage<ProcessInstance>> result = new Result<IPage<ProcessInstance>>();
        QueryWrapper<ProcessInstance> queryWrapper = QueryGenerator.initQueryWrapper(processInstance, req.getParameterMap());

        Page<ProcessInstance> page = new Page<ProcessInstance>(pageNo, pageSize);
        IPage<ProcessInstance> pageList = processInstanceService.page(page, queryWrapper);
        for (ProcessInstance p : pageList.getRecords()) {
            //申请人名称
            VeBaseAppUser veBaseAppUser = iVeBaseAppUserService.getAppUserByUserId(p.getApplicantId());
            if (veBaseAppUser != null) {
                p.setApplicantName(veBaseAppUser.getRealName());
            }
            //流程名称
            ProcessType processType = iProcessTypeService.getById(p.getProcessTypeId());
            if (processType != null) {
                p.setProcessTypeName(processType.getName());
            }
            //获取审批人名称
            LambdaQueryWrapper<ProcessStep> processStepLambdaQueryWrapper = new LambdaQueryWrapper<>();
            processStepLambdaQueryWrapper.eq(ProcessStep::getStepOrder,p.getCurrentStep());
            processStepLambdaQueryWrapper.eq(ProcessStep::getProcessTypeId,p.getProcessTypeId());
            ProcessStep processStep = iProcessStepService.getOne(processStepLambdaQueryWrapper);
            if (processStep != null) {
                p.setCurrentApproveName(processStep.getApproverValue());
                p.setCurrentStepName(processStep.getStepName());
            }
            //当前状态名称
            if (p.getCurrentStatus() != null) {
                if (p.getCurrentStatus().equals("pending")) {
                    p.setCurrentStatusName("待审批");
                } else if (p.getCurrentStatus().equals("processing")) {
                    p.setCurrentStatusName("审批中");
                } else if (p.getCurrentStatus().equals("approved")) {
                    p.setCurrentStatusName("已通过");
                }else if (p.getCurrentStatus().equals("rejected")) {
                    p.setCurrentStatusName("已拒绝");
                }else if (p.getCurrentStatus().equals("canceled")) {
                    p.setCurrentStatusName("已取消");
                }else{
                    p.setCurrentStatusName("未知状态");
                }
            }
        }
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }
    /**
     * 审批列表
     *
     * @param processInstance
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "流程实例表-审批列表")
    @ApiOperation(value = "流程实例表-审批列表", notes = "流程实例表-审批列表")
    @GetMapping(value = "/pendingApprovals")
    public Result<IPage<ProcessInstance>> pendingApprovals(ProcessInstance processInstance,
                                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                        HttpServletRequest req) {
        Result<IPage<ProcessInstance>> result = new Result<IPage<ProcessInstance>>();

        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (user == null){
            throw new ServiceException("登录已过期，请重新登录");
        }

        String userId = user.getUsername();
        Page<ProcessInstance> page = new Page<ProcessInstance>(pageNo, pageSize);
        IPage<ProcessInstance> pageList = new Page<>();
        if (processInstance.getCurrentStatus()!=null){
            if (processInstance.getCurrentStatus().equals("pending")) {
                pageList = processInstanceService.spGetDblcPage(page, userId);
            }else if (processInstance.getCurrentStatus().equals("approved")) {
                pageList = processInstanceService.spGetYblcPage(page, userId);
            }
        }else {
//            throw new ServiceException("缺少currentStatus参数");
            pageList = processInstanceService.getMyApprovals(page,JSONUtil.toJsonStr(processInstance),userId);
        }
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 我发起的流程
     *
     * @param processInstance
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "流程实例表-我发起的流程")
    @ApiOperation(value = "流程实例表-我发起的流程", notes = "流程实例表-我发起的流程")
    @GetMapping(value = "/myProcess")
    public Result<IPage<ProcessInstance>> myProcess(ProcessInstance processInstance,
                                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                           HttpServletRequest req) {
        Result<IPage<ProcessInstance>> result = new Result<IPage<ProcessInstance>>();

        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (user == null){
            throw new ServiceException("登录已过期，请重新登录");
        }
        processInstance.setApplicantId(user.getUserId());
        Page<ProcessInstance> page = new Page<ProcessInstance>(pageNo, pageSize);
        IPage<ProcessInstance> pageList = processInstanceService.getMyCreateProcess(page, JSONUtil.toJsonStr(processInstance), user.getUserId());
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }


    /**
     * 各流程占比
     *
     * @param processInstance
     * @return
     */
    @AutoLog(value = "流程实例表-各流程占比")
    @ApiOperation(value = "流程实例表-各流程占比", notes = "流程实例表-各流程占比")
    @GetMapping(value = "/processProportion")
    public Result<Map> processProportion(ProcessInstance processInstance) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (user == null){
            throw new ServiceException("登录已过期，请重新登录");
        }
        Map resMap = new HashMap();
        List<Map> maps = processInstanceService.countGroupByTypeId();
        resMap.put("list", maps);
        Integer total = processInstanceService.count();
        resMap.put("total", total);
//        Map totalMap = new HashMap();
//        totalMap.put("name", "总数");
//        totalMap.put("value", total);
//        maps.add(totalMap);
        return Result.OK(resMap);
    }

    /**
     * 待办、已办、我申请的、通知数量统计
     *
     * @return
     */
    @AutoLog(value = "流程实例表-待办、已办、我申请的、通知数量统计")
    @ApiOperation(value = "流程实例表-待办、已办、我申请的、通知数量统计", notes = "流程实例表-待办、已办、我申请的、通知数量统计")
    @GetMapping(value = "/countProcess")
    public Result<List<Map>> countProcess() {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (user == null){
            throw new ServiceException("登录已过期，请重新登录");
        }
        List<Map> maps = new ArrayList<>();
        String userId = user.getUsername();
        //待办
        Integer dblc = processInstanceService.countDblc(userId);
        Map dblcMap = new HashMap();
        dblcMap.put("name","待办");
        dblcMap.put("value",dblc);
        maps.add(dblcMap);
        //已办
        Integer yblc = processInstanceService.countYblc(userId);
        Map yblcMap = new HashMap();
        yblcMap.put("name","已办");
        yblcMap.put("value",yblc);
        maps.add(yblcMap);
        //我申请的
        Long myCreate = processInstanceService.countMyCreate(null,userId);
        Map myCreateMap = new HashMap();
        myCreateMap.put("name","我申请的");
        myCreateMap.put("value",myCreate);
        maps.add(myCreateMap);
        //通知
        Page<SysAnnouncement> anntMsgList = new Page<SysAnnouncement>(0,5);
        anntMsgList = sysAnnouncementService.querySysCementPageByUserId(anntMsgList,userId,"1");//通知公告消息
        Long anntCount = anntMsgList.getTotal();
        Map anntMap = new HashMap();
        anntMap.put("name","通知");
        anntMap.put("value",anntCount);
        maps.add(anntMap);
        return Result.OK(maps);
    }

    /**
     * 添加
     *
     * @param processInstance
     * @return
     */
    @AutoLog(value = "流程实例表-添加")
    @ApiOperation(value = "流程实例表-添加", notes = "流程实例表-添加")
    @PostMapping(value = "/save")
    public Result<ProcessInstance> save(@RequestBody ProcessInstance processInstance) {
        Result<ProcessInstance> result = new Result<ProcessInstance>();
        try {
            processInstanceService.save(processInstance);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑
     *
     * @param updateProcessRequest
     * @return
     */
    @AutoLog(value = "流程实例表-编辑")
    @ApiOperation(value = "流程实例表-编辑", notes = "流程实例表-编辑")
    @PutMapping(value = "/edit")
    public Result<ProcessInstance> edit(@RequestBody UpdateProcessRequest updateProcessRequest) {
        Result<ProcessInstance> result = new Result<ProcessInstance>();
        ProcessInstance processInstanceEntity = processInstanceService.getById(updateProcessRequest.getId());
        if (processInstanceEntity == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = processInstanceService.updateById(processInstanceEntity);
            //更新表单
            LambdaUpdateWrapper<ProcessFormData> processFormDataLambdaQueryWrapper = new LambdaUpdateWrapper<>();
            processFormDataLambdaQueryWrapper.eq(ProcessFormData::getInstanceId,updateProcessRequest.getId());
            processFormDataLambdaQueryWrapper.set(ProcessFormData::getFormData,updateProcessRequest.getFormData().toJSONString());
            iProcessFormDataService.update(processFormDataLambdaQueryWrapper);
            //TODO 返回false说明什么？
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }

    /**
     * 发起流程
     *
     * @param createProcessRequest
     * @return
     */
    @AutoLog(value = "流程实例表-发起流程")
    @ApiOperation(value = "流程实例表-发起流程", notes = "流程实例表-发起流程")
    @PostMapping(value = "/createProcess")
    public Result<ProcessInstance> createProcess(@RequestBody CreateProcessRequest createProcessRequest) {
        Result<ProcessInstance> result = new Result<ProcessInstance>();
        try {
            Integer processTypeId = createProcessRequest.getProcessTypeId();
            if (processTypeId == null) {
                return result.error500("流程类型id缺失");
            }
            String applicantId = createProcessRequest.getApplicantId();
            if (applicantId == null) {
                return result.error500("申请人用户id缺失");
            }
            String formData = "";
            JSONObject formDataObject = createProcessRequest.getFormData();
            if (formDataObject == null) {
                return result.error500("表单数据缺失");
            } else {
                formData = JSON.toJSONString(formDataObject);
            }
            processInstanceService.createProcess(processTypeId, applicantId, formData);
            result.success("流程创建成功");
        } catch (DataAccessException e) {
            result.error500(e.getCause().getMessage());
        }
        return result;
    }

    /**
     * 审批不通过重新提交
     *
     * @param resubmitProcess
     * @return
     */
    @AutoLog(value = "流程实例表-审批不通过重新提交")
    @ApiOperation(value = "流程实例表-审批不通过重新提交", notes = "流程实例表-审批不通过重新提交")
    @PostMapping(value = "/resubmitProcess")
    public Result<ProcessInstance> resubmitProcess(@RequestBody() ResubmitProcess resubmitProcess) {
        Result<ProcessInstance> result = new Result<ProcessInstance>();
        try {
            Integer instanceId = resubmitProcess.getId();
            if (instanceId == null) {
                return result.error500("流程实例id缺失");
            }
            String applicantId = resubmitProcess.getApplicantId();
            if (applicantId == null) {
                return result.error500("申请人用户id缺失");
            }
            JSONObject formDataJsonObject = resubmitProcess.getFormData();
            if (formDataJsonObject == null) {
                return result.error500("表单数据缺失");
            }
            processInstanceService.resubmitProcess(instanceId, applicantId, formDataJsonObject.toJSONString());
            result.success("重新提交成功");
        } catch (DataAccessException e) {
            result.error500(e.getCause().getMessage());
        }
        return result;
    }

    /**
     * 审批
     *
     * @return
     */
    @AutoLog(value = "流程实例表-审批")
    @ApiOperation(value = "流程实例表-审批", notes = "流程实例表-审批")
    @PostMapping(value = "/approveProcess")
    public Result<ProcessInstance> approveProcess(@RequestBody ApproveProcessRequest approveProcessRequest) {
        Result<ProcessInstance> result = new Result<ProcessInstance>();
        try {
            Integer instanceId = approveProcessRequest.getInstanceId();
            String approverId = approveProcessRequest.getApproverId();
            if (approverId == null) {
                LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                approverId = user.getUsername();
            }
            String approvalResult = approveProcessRequest.getApprovalResult();
            String comment = approveProcessRequest.getComment();
            processInstanceService.approveProcess(instanceId, approverId, approvalResult, comment);
            result.success("审批成功");
        } catch (DataAccessException sqlException) {
            result.error500(sqlException.getCause().getMessage());
        }
        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "流程实例表-通过id删除")
    @ApiOperation(value = "流程实例表-通过id删除", notes = "流程实例表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        try {
            processInstanceService.removeById(id);
        } catch (Exception e) {
            log.error("删除失败", e.getMessage());
            return Result.error("删除失败!");
        }
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "流程实例表-批量删除")
    @ApiOperation(value = "流程实例表-批量删除", notes = "流程实例表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<ProcessInstance> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<ProcessInstance> result = new Result<ProcessInstance>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.processInstanceService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "流程实例表-通过id查询")
    @ApiOperation(value = "流程实例表-通过id查询", notes = "流程实例表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<Map> queryById(@RequestParam(name = "id", required = true) Integer id) {
        Result<Map> result = new Result<Map>();
        Map processInstanceMap = processInstanceService.getProcessInstance(id);
        if (processInstanceMap == null) {
            result.error500("未找到对应流程信息");
        } else {
            result.setResult(processInstanceMap);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
        // Step.1 组装查询条件
        QueryWrapper<ProcessInstance> queryWrapper = null;
        try {
            String paramsStr = request.getParameter("paramsStr");
            if (oConvertUtils.isNotEmpty(paramsStr)) {
                String deString = URLDecoder.decode(paramsStr, "UTF-8");
                ProcessInstance ProcessInstance = JSON.parseObject(deString, ProcessInstance.class);
                queryWrapper = QueryGenerator.initQueryWrapper(ProcessInstance, request.getParameterMap());
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<ProcessInstance> pageList = processInstanceService.list(queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "流程实例表列表");
        mv.addObject(NormalExcelConstants.CLASS, ProcessInstance.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("流程实例表列表数据", "导出人:Jeecg", "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        // 错误信息
        List<String> errorMessage = new ArrayList<>();
        int successLines = 0, errorLines = 0;
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<Object> listProcessInstances = ExcelImportUtil.importExcel(file.getInputStream(), ProcessInstance.class, params);
                List<String> list = ImportExcelUtil.importDateSave(listProcessInstances, IProcessInstanceService.class, errorMessage, CommonConstant.SQL_INDEX_UNIQ_CODE);
                errorLines += list.size();
                successLines += (listProcessInstances.size() - errorLines);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return ImportExcelUtil.imporReturnRes(errorLines, successLines, errorMessage);
    }

    //    @PostMapping
//    public ResponseEntity<?> createProcessConfig(
//            @RequestBody ProcessConfigRequest request) {
//
//        // 参数校验
//        if (request.getProcessInstance() == null
//                || CollectionUtils.isEmpty(request.getSteps())) {
//            return ResponseEntity.badRequest().body("参数不完整");
//        }
//
//        try {
//            processConfigService.saveProcessConfig(
//                    request.getProcessInstance(),
//                    request.getSteps()
//            );
//            return ResponseEntity.ok("配置保存成功");
//        } catch (Exception e) {
//            return ResponseEntity.badRequest()
//                    .body(e.getMessage());
//        }
//    }
//

    /**
     * 发起流程请求体
     */
    @Data
    static class CreateProcessRequest {
        private Integer processTypeId;
        private String applicantId;
        private JSONObject formData;
    }

    /**
     * 被驳回重新发起流程请求体
     */
    @Data
    static class ResubmitProcess {
        private Integer id;
        private String applicantId;
        private JSONObject formData;
    }
    /**
     * 修改流程请求体
     */
    @Data
    static class UpdateProcessRequest {
        private Integer id;
        private String applicantId;
        private JSONObject formData;
    }

    /**
     * 审批流程请求体
     */
    @Data
    static class ApproveProcessRequest {
        private Integer instanceId;
        private String approverId;
        private String approvalResult;
        private String comment;
    }
}
